package com.sicheng.algorithm.node;

public class Reverse {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        init(head);
        output(head);
        output(reverse(head));
    }


    public static ListNode reverse(ListNode head) {
        if (head == null || head.next == null)
            throw new RuntimeException("链表长度不大于1");
        ListNode first = head.next;
        head.next = null;
        ListNode next;
        while (first.next != null) {
            next = first.next;
            first.next = head;
            head = first;
            first = next;
        }
        first.next=head;
        head = first;
        return head;
    }


    public static void init(ListNode head) {
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        head.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
    }

    public static void output(ListNode head) {

        if (head == null)
            return;
        ListNode temp = head;
        while (temp.next != null) {
            System.out.println(temp);
            temp = temp.next;
        }
        System.out.println(temp);
    }
}
